package com.campus.controller;

import com.campus.model.User;
import com.campus.service.UserService;

import com.campus.web.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/homework/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public ResponseResult<String> addUserWithRole(@RequestBody Map<String, Object> request) {
        // 解析请求参数
        Map<String, Object> userData = (Map<String, Object>) request.get("user");
        Integer roleId = (Integer) request.get("roleId");

        if (userData == null || roleId == null) {
            return ResponseResult.error(HttpStatus.BAD_REQUEST, "Invalid request body");
        }

        // 创建 User 对象
        User user = new User()
                .setLoginName((String) userData.get("loginName"))
                .setPassword((String) userData.get("password"))
                .setGender((String) userData.get("gender"))
                .setBirthday(userData.get("birthday") != null ? java.sql.Date.valueOf((String) userData.get("birthday")) : null)
                .setPhone((String) userData.get("phone"))
                .setEmail((String) userData.get("email"))
                .setStatus((String) userData.get("status"));

        // 调用 Service
        if (userService.createUserWithRole(user, roleId)) {
            return ResponseResult.ok("User created successfully!");
        } else {
            return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to create user.");
        }
    }

    // 根据 ID 查询用户
    @GetMapping("/{id}")
    public ResponseResult<User> getUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        return user != null ? ResponseResult.ok(user) : ResponseResult.error(HttpStatus.NOT_FOUND, "User not found.");
    }

    // 根据用户名查询用户
    @GetMapping("/search")
    public ResponseResult<User> getUserByLoginName(@RequestParam String loginName) {
        Optional<User> user = userService.getUserByLoginName(loginName);
        return user.map(ResponseResult::ok).orElseGet(() -> ResponseResult.error(HttpStatus.NOT_FOUND, "User not found."));
    }

    // 修改用户信息
    @PutMapping("/update/{id}")
    public ResponseResult<String> updateUser(@PathVariable Integer id, @RequestBody Map<String, Object> userData) {
        User user = new User()
                .setId(id)
                .setLoginName((String) userData.get("loginName"))
                .setPassword((String) userData.get("password"))
                .setGender((String) userData.get("gender"))
                .setBirthday(userData.get("birthday") != null ? java.sql.Date.valueOf((String) userData.get("birthday")) : null)
                .setPhone((String) userData.get("phone"))
                .setEmail((String) userData.get("email"))
                .setStatus((String) userData.get("status"));

        if (userService.updateUser(user)) {
            return ResponseResult.ok("User updated successfully!");
        } else {
            return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to update user.");
        }
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public ResponseResult<String> deleteUser(@PathVariable Integer id) {
        if (userService.deleteUser(id)) {
            return ResponseResult.ok("User deleted successfully!");
        } else {
            return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to delete user.");
        }
    }

    // 查询所有用户
    @GetMapping("/list")
    public ResponseResult<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        if (users != null && !users.isEmpty()) {
            return ResponseResult.ok(users);
        } else {
            return ResponseResult.error(HttpStatus.NOT_FOUND, "No users found.");
        }
    }

}
